import React, { Fragment, useState, Suspense, lazy, useRef, useEffect } from "react";
import { Row, Col, Typography, DatePicker, Select, Spin } from 'antd';
import { LoadingOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
import isToday from 'dayjs/plugin/isToday';
import { range_time } from "../../utils/chartUtils";
dayjs.extend(isToday)

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;

const DynamicLineChart = lazy(() => import('./LineChart'));
const Loading = () => (
  <Spin
    indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />}
    tip='图形加载中...'
  />
)

const rangePresets = [
  { label: '昨天', value: [dayjs().add(-1, 'd'), dayjs()] },
  { label: '前三天', value: [dayjs().add(-3, 'd'), dayjs()] },
  { label: '上一周', value: [dayjs().add(-7, 'd'), dayjs()] },
]

const waitTime = (time) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        { time: 1709222400, body: '50' },
        { time: 1711900800, body: '2' },
        { time: 1713888000, body: '5' },
        { time: 1713888000, body: '66' },
        { time: 1714059859, body: '24' },
      ]);
    }, time);
  });
};

const TargetLog = ({
  title: chartTitle,
  meter,
  showLazy,
}) => {

  const lineRef = useRef(null);
  const [chartData, setChartData] = useState([]);
  const [rangeValue, setRangeValue] = useState([dayjs().startOf('day'), dayjs()]);
  const [stepValue, setStepValue] = useState('600');

  const getChartData = async (timeParams) => {
    const params = {
      startTime: dayjs()?.startOf('day')?.valueOf(),
      endTime: dayjs()?.valueOf(),
      meter,
      ...timeParams,
    }
    const handleData = await waitTime(2000, params);
    return handleData
  }

  const initChartList = async () => {
    const handleData = await getChartData();
    setChartData(handleData)
  }

  useEffect(() => {
    if (showLazy) initChartList();
  }, [showLazy])

  const handleChangeChartData = async (updateParams) => {
    const handleData = await getChartData(updateParams);
    if (lineRef.current) {
      lineRef.current?.changeChartData(handleData)
    }
  }

  const onChangeSelect = (newValue) => {
    setStepValue(newValue);
    const updateChart = {
      startTime: rangeValue?.[0]?.valueOf(),
      endTime: rangeValue?.[1]?.valueOf(),
      step: newValue,
    }
    handleChangeChartData(updateChart);
  }

  const onChangeRangePicker = async (dates) => {
    setRangeValue(dates)
    const updateChart = {
      startTime: dates ? dates?.[0]?.valueOf() : dayjs()?.startOf('day')?.valueOf(),
      endTime: dates ? dates?.[1]?.valueOf() : dayjs()?.valueOf(),
      step: stepValue,
    }
    handleChangeChartData(updateChart);
  }

  const disabledDate = (date) => {
    return date && date > dayjs().endOf('day')
  }

  const disabledRangeTime = (date) => {
    if (date.isToday()) {
      const curHour = dayjs().hour() + 1;
      const curMinute = dayjs().minute() + 1;
      const curSecond = dayjs().second() + 1;
      const curMillisecond = dayjs().millisecond() + 1;
      return {
        disableHours: () => range_time(curHour, 24),
        disableMinutes: () => range_time(curMinute, 24),
        disableSeconds: () => range_time(curSecond, 24),
        disableMilliseconds: () => range_time(curMillisecond, 24),
      }
    } else {
      return {
        disableHours: () => [],
        disableMinutes: () => [],
        disableSeconds: () => [],
        disableMilliseconds: () => [],
      }
    }
  }

  return (
    <Fragment>
      <Title level={5}>{chartTitle}</Title>
      <Row wrap gutter={[16, 16]}>
        <Col>
          <Text>日期：</Text>
          <RangePicker
            allowClear
            disabledDate={disabledDate}
            disabledTime={disabledRangeTime}
            showTime={{
              hideDisabledOptions: true,
              defaultValue: [dayjs('00:00:00', 'HH:mm'), dayjs()],
            }}
            presets={[
              {
                label: <span>当前开始时间</span>,
                value: () => [dayjs().startOf('day'), dayjs()],
              },
              ...rangePresets
            ]}
            format='YYYY-MM-DD HH:mm'
            onChange={onChangeRangePicker}
            value={rangeValue} s
          />
        </Col>
        <Col>
          <Text>区间：</Text>
          <Select
            value={stepValue}
            style={{ width: 120 }}
            onChange={onChangeSelect}
            options={[
              { value: '60', label: '1分钟' },
              { value: '300', label: '5分钟' },
              { value: '600', label: '10分钟' },
              { value: '1200', label: '20分钟' },
              { value: '1800', label: '30分钟' },
              { value: '3600', label: '1小时' },
            ]}
          />
        </Col>
        <Col span={24}>
          <Suspense
            fallback={<Loading />}
          >
            <DynamicLineChart
              ref={lineRef}
              chartData={chartData}
              meter={meter}
            />
          </Suspense>
        </Col>
      </Row>
    </Fragment>
  )
}

export default TargetLog